import Model from './Model.js'
import View from './View.js'
import { AStar, Node } from './util/AStar.js'
// import Controller from './Controller.js'

class Game {
    constructor(cvs, xCount, yCount, width, height) {
        this.xCount = xCount
        this.yCount = yCount

        this.cvs = cvs
        this.ctx = cvs.getContext('2d')
        this.model = new Model(xCount, yCount, width, height)
        this.view = new View(this.ctx, this.model)
        // this.handlerKeyBoard.bind(this)
        this.timer = null
        this.frame_time = 50 // ms
        this.status = true // 状态进行（true）停止（fales）
        this.direction = 'right' // 方向
        this.route = []
        this.astar = null
        // this.initEvent()
        this.initGame()
    }

    initEvent() {
        
        window.addEventListener('keydown', this.handlerKeyBoard.bind(this))
    }

    handlerKeyBoard(e) {
        
        if (e.key === 'ArrowUp') {
            if (this.direction === 'down') return
            this.direction = 'up'
        }
        if (e.key === 'ArrowDown') {
            if (this.direction === 'up') return
            this.direction = 'down'
        }
        if (e.key === 'ArrowLeft') {
            if (this.direction === 'right') return
            this.direction = 'left'
        }
        if (e.key === 'ArrowRight') {
            if (this.direction === 'left') return
            this.direction = 'right'
        }
       
        if (e.key === 'p' || e.key === 'P') {
            this.pause('pause')
        }
    }

    go(direction) {
        console.log(direction);
        if (!this.status) {
            return
        }
        const snake = this.model.snake
        this.direction = direction
        if (direction === 'up') {
            snake.moveUp()
            this.view.repait()
        }
        if (direction === 'down') {
            snake.moveDown()
            this.view.repait()
        }
        if (direction === 'left') {
            snake.moveLeft()
            this.view.repait()
        }
        if (direction === 'right') {
            snake.moveRight()
            this.view.repait()
        }

        this.collision_detection()
        
    }

    /**
     * 碰撞检测，判断是否是食物或者是边界（墙）
     */
    collision_detection() {
        const head = this.model.snake.head
        const items = this.model.snake.toList()

        const over = head.x < 0 || head.y < 0
                    || head.x >= this.xCount || head.y >= this.yCount

        // console.log(over);
        const isD = items.some(item => {
            return head.x === item.x && head.y === item.y && item !== head
        })

        if (over || isD) {
            console.log('Game over');
            this.pause('Game over')

        }


        const food = this.model.food
        
        const isFood = head.x === food.x && head.y === food.y
        if (isFood) {
            this.model.snake.eat(food)
            this.view.repait()
            // this.go(this.direction)
            const {x, y} = this.model.initFood()
            const start = new Node(head.x, head.y)

            const target = new Node(x, y)
            this.search(start, target)
            // console.log(routes);
            this.view.repait()
        }
    }

    search(start, target) {
        const list = this.model.snake.toList()
        const astar = new AStar(this.xCount, this.yCount, list)
        const lastNode = astar.search(start, target)
        const routes = astar.toList(lastNode)
        console.log(routes);
        this.autoGo(routes)
    }

    autoGo(list) {
        if (list.length === 0) {
            this.view.drawText('无法进行下一步')
        }
        // console.log(list);
        const direction = []

        for (let index = 0; index < list.length - 1; index++) {
            const cur = list[index];
            const next = list[index + 1];
            if (cur.x === next.x) {
                if (cur.y < next.y)
                    direction.push('down')
                else 
                    direction.push('up')
                continue
            }

            if (cur.y === next.y) {
                if (cur.x < next.x)
                    direction.push('right')
                else 
                    direction.push('left')
                continue
            }
        }
        // console.log(direction);

        // let index = 0

        for (let i = 0; i < direction.length; i++) {
            const element = direction[i];
            setTimeout(() => {
                this.go(element)
            }, i * this.frame_time)
            
        }
        // setInterval(this.go(direction[index++]), this.frame_time)

        // direction.forEach(item => {
        //     this.go(item)
        // })
        
    }

    

    initGame() {
        const snake = [
            {x: 2, y: 0},
            {x: 1, y: 0},
            {x: 0, y: 0},
        ]
        this.model.createSnake(snake)
        // this.model.initFood()
        const head = this.model.snake.head
        const {x, y} = this.model.initFood()
        const start = new Node(head.x, head.y)
        const target = new Node(x, y)

        this.search(start, target)
            // console.log(routes);
            // this.view.repait()
        this.view.create(this.width, this.height)
    }

    start() {
        // this.go(this.direction)
        // if (this.timer) {
        //     clearInterval(this.timer)
        // }
        // this.timer = setInterval(() => {
        //     this.go(this.direction)
        // }, this.frame_time)

        // this.initGame()
    }

    pause(msg) {
        // this.view.clear()
        this.status = !this.status
        console.log('pause:' + this.status);
        if (!this.status) {
            this.view.repait()
            this.view.drawText(msg)
            clearInterval(this.timer)
        } else {
            this.start()
        }
    }
}

export default Game